package com.wl.lib.http

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


// Created by wangliang on 2024/4/25.
object CommonRetrofitClient {
    private const val TAG = "CommonRetrofitClient"

    private const val DEFAULT_TIMEOUT_MS = 12000L

    private val defaultOkHttpClient = OkHttpClient.Builder()
        .connectTimeout(DEFAULT_TIMEOUT_MS, TimeUnit.SECONDS)
        .readTimeout(DEFAULT_TIMEOUT_MS, TimeUnit.SECONDS)
        .writeTimeout(DEFAULT_TIMEOUT_MS, TimeUnit.SECONDS)
        .addInterceptor(
            HttpLoggingInterceptor { message -> Log.d(TAG, message) }.setLevel(
                HttpLoggingInterceptor.Level.BODY
            )
        ).build()

    private val defaultBaseUrl: String
        get() {
            if (DomainManager.mainDomain == null) {
                throw RuntimeException("main domain is null, please set DomainManager.mainDomain.")
            }
            return DomainManager.mainDomain!!
        }

    private val defaultRetrofit: Retrofit by lazy {
        Retrofit.Builder()
            .client(defaultOkHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(defaultBaseUrl)
            .build()
    }

    @JvmOverloads
    fun retrofit(baseUrl: String = defaultBaseUrl, timeout: Long = DEFAULT_TIMEOUT_MS): Retrofit {
        if (defaultRetrofit.baseUrl().toString() == baseUrl && timeout == DEFAULT_TIMEOUT_MS) {
            return defaultRetrofit
        }
        val okHttpClient = if (timeout == DEFAULT_TIMEOUT_MS) {
            defaultOkHttpClient
        } else {
            defaultOkHttpClient.newBuilder()
                .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                .readTimeout(timeout, TimeUnit.MILLISECONDS)
                .writeTimeout(timeout, TimeUnit.MILLISECONDS)
                .build()
        }
        return Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(baseUrl)
            .build()
    }

    fun <T> create(serviceClass: Class<T>): T {
        return retrofit().create(serviceClass)
    }
}